<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Using Direct Line Speech</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- Direct Line Speech adapter set is only available in full bundle -->
    <!--
      This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to using Web Chat's latest bits:
      https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
    -->
    <script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
      html,
      body {
        height: 100%;
      }

      body {
        margin: 0;
      }

      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>

  <body>
    <div id="webchat" role="main"></div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line Speech token from MockBot.
        // Your client code must provide either a secret or a token to talk to your bot.
        // Tokens are more secure. To learn about the differences between secrets and tokens
        // and to understand the risks associated with using secrets, visit https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0

        // This function will fetch speech token from a server.
        // In our server, we call Cognitive Services to exchange subscription key into authorization token.
        // Visit https://docs.microsoft.com/en-us/azure/cognitive-services/authentication for more details.
        const fetchCredentials = async () => {
          const res = await fetch('https://webchat-mockbot-streaming.azurewebsites.net/speechservices/token', {
            method: 'POST'
          });

          if (!res.ok) {
            throw new Error('Failed to fetch authorization token and region.');
          }

          const { region, token: authorizationToken } = await res.json();

          return { authorizationToken, region };
        };

        // Create a set of adapters for Web Chat to use with Direct Line Speech channel.
        // Please refer to /packages/directlinespeech/src/createAdapters.js for list of supported options.
        const adapters = await window.WebChat.createDirectLineSpeechAdapters({
          fetchCredentials
        });

        // Pass the set of adapters to Web Chat.
        window.WebChat.renderWebChat(
          {
            ...adapters
          },
          document.getElementById('webchat')
        );

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>
